import { _decorator, Color, Component, Label, tween, Vec3, v3, UITransform, UIOpacity } from 'cc';
import ObjectPoolManager from './ObjectPoolManager';
import { EText } from '../Config/Enum';
const { ccclass } = _decorator;

@ccclass('NumberText')
export class NumberText extends Component {
    label: Label;

    protected onLoad(): void {
        this.label = this.node.getComponent(Label);
    }

    static show(text: string, worldPosition: Vec3, color: Color = Color.WHITE, scale=1,duration: number = 1, isCritical: boolean = false) {
        //console.log("NumberText show worldPosition", worldPosition);
        
        let node = ObjectPoolManager.Instance.get(EText.Text);
        const opacity = node.getComponent(UIOpacity);
        opacity.opacity = 255; // 确保每次显示时透明度为255
        
        // 设置初始缩放
        node.scale = v3(scale, scale, scale);
        
        // 添加随机偏移避免重叠
        const randomOffsetX = (Math.random() - 0.5) * 20; // 随机偏移
        const randomOffsetY = (Math.random() - 0.5) * 50; // 随机偏移
        
        node.setWorldPosition(
            worldPosition.x + randomOffsetX, 
            worldPosition.y + 30 + randomOffsetY, 
            worldPosition.z
        );
        
        let numberText = node.getComponent(NumberText);
        const labelComponent = numberText.label;
        labelComponent.color = color;
        labelComponent.string = text;

        // 动画参数
        const floatDistance = 30; // 向上飘的距离
        const scaleUp = scale*1.3; // 放大效果
        const peakTime = 0.3; // 到达最大缩放的时间

        // 计算目标位置（转换为局部坐标）
        const currentLocalPos = node.position.clone();
        const targetLocalPos = v3(currentLocalPos.x, currentLocalPos.y + floatDistance, currentLocalPos.z);

        // 缩放动画：先放大后缩小
        const scaleTween = tween(node)
            .to(peakTime, { scale: v3(scaleUp, scaleUp, 1) }) // 放大到峰值
            .to(duration - peakTime, { scale: v3(0.5, 0.5, 1) }); // 缩小到0.5倍

        // 位移动画：匀速上浮
        const moveTween = tween(node)
            .to(duration, { position: targetLocalPos }, { easing: 'sineOut' });

        // 透明度动画：渐隐
        const fadeTween = tween(opacity)
            .to(duration, { opacity: 0 });

        // 并行执行所有动画
        tween(node)
            .parallel(scaleTween, moveTween, fadeTween)
            .call(() => ObjectPoolManager.Instance.ret(node)) // 动画完成后回收
            .start();
    }
}